{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Floor and Ceiling of a Binary Search Tree\n",
    "\n",
    "[The Original Question](https://mp.weixin.qq.com/s/5Ca79veFEa87KO69AOAqzw)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "Given an integer `k` and a binary search tree, find the floor of (less than or equal to) `k` and the ceiling of (larger than or equal to) `k`. If either does not exist, then print them as `None`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Node:\n",
    "    def __init__(self, value):\n",
    "        self.left = None\n",
    "        self.right = None\n",
    "        self.value = value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def findCeilingFloor(root_node: Node, k, floor=None, ceil=None):\n",
    "    if root_node is None:\n",
    "        return (floor, ceil)\n",
    "    elif root_node.value == k:\n",
    "        return (root_node.value,) * 2\n",
    "    if root_node.value < k:\n",
    "        floor = root_node.value\n",
    "        return findCeilingFloor(root_node.right, k, floor, ceil)\n",
    "    elif root_node.value > k:\n",
    "        ceil = root_node.value\n",
    "        return findCeilingFloor(root_node.left, k, floor, ceil)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(4, 6)\n"
     ]
    }
   ],
   "source": [
    "root = Node(8)\n",
    "root.left = Node(4)\n",
    "root.right = Node(12)\n",
    "root.left.left = Node(2)\n",
    "root.left.right = Node(6)\n",
    "root.right.left = Node(10)\n",
    "root.right.right = Node(14)\n",
    "print(findCeilingFloor(root, 5))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
